package com.chenfan.ccp.util.sign;

import com.jcraft.jsch.Session;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.transport.JschConfigSessionFactory;
import org.eclipse.jgit.transport.OpenSshConfig;
import org.eclipse.jgit.transport.SshSessionFactory;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import org.springframework.core.io.PathResource;
import org.springframework.core.io.Resource;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Map;
import java.util.Properties;


/**
 * 配置的中心工具
 */
public class ConfigGitUtil {

    static {
        SshSessionFactory.setInstance(new JschConfigSessionFactory() {
            @Override
            public void configure(OpenSshConfig.Host hc, Session session) {
                session.setConfig("StrictHostKeyChecking", "no")
                ;
            }

        });
    }

    private ConfigGitUtil() {

    }


    public static ConfigGitUtil getInstance() {
        return ConfigGitUtilHolder.INSTANCE;
    }


    public Resource getResource(String fileName) {
        return new PathResource(ConfigGitUtilHolder.LOCAL_REPOSITORY + File.separator + fileName);
    }

    public void addParam(Map<String, String> param, String fileName, String userName, String userPass) {
        ConfigGitUtilHolder.push(param, fileName, userName, userPass);
    }

    private static class ConfigGitUtilHolder {
        private static final String REMOTE_PATH = "http://10.228.81.113:18000/pengjian/chenfan-authorize-file.git";
        private static final String LOCAL_REPOSITORY = System.getProperty("java.io.tmpdir") + File.separator + "_git_config_" + System.currentTimeMillis();
        private static final ConfigGitUtil INSTANCE = new ConfigGitUtil();

        static {
            File file = new File(LOCAL_REPOSITORY);
            if (file.exists()) {
                deleteDirect(file);

            }

            try {
                gitClone();
            } catch (GitAPIException e) {
                throw new RuntimeException(e);
            }
        }

        /**
         * 克隆远程库
         */
        private static void gitClone() throws GitAPIException {
            Git.cloneRepository().setURI(ConfigGitUtilHolder.REMOTE_PATH).setBranch("master").
                    setDirectory(new File(LOCAL_REPOSITORY)).call();

        }

        private static void push(Map<String, String> param, String fileName, String name, String pass) {

            try {
                Properties properties = new Properties();
                for (String key : param.keySet()) {
                    if (param.get(key) == null) {
                        continue;
                    }
                    properties.setProperty(key, param.get(key));
                }

                OutputStream fos = new FileOutputStream(new File(LOCAL_REPOSITORY, fileName));
                properties.store(fos, properties.toString());
                Git git = Git.open(new File(LOCAL_REPOSITORY));
                git.pull().call();
                git.add().addFilepattern(fileName).call();
                git.commit().setMessage(fileName).call();
                git.push().setCredentialsProvider(new
                        UsernamePasswordCredentialsProvider(name, pass)).call();

                fos.close();

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        /**
         * 递归删除空目录
         *
         * @param file 文件夹
         */
        private static void deleteDirect(File file) {
            File[] childFile = file.listFiles();

            //分级删除
            for (File tmpFile : childFile) {

                if (tmpFile.isDirectory()) {
                    deleteDirect(tmpFile);
                } else {
                    tmpFile.delete();
                }
            }

            //删除此目录
            if (file.isDirectory()) {
                file.delete();
            }
        }


    }
}
